﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RapidWebDev.UI.DynamicPages;
using RapidWebDev.UI.Controls;
using TestCenter.Platform.Apis;
using RapidWebDev.Platform;
using RapidWebDev.Common;
using TestCenter.Platform.DataModel;
using RapidWebDev.UI;
using RapidWebDev.Common.Data;

namespace TestCenter.Platform.Web.DynamicPages
{
    public class TestProjectDetail : DetailPanelPage
    {
        protected static readonly ITestCenterApi testcenterApi = SpringContext.Current.GetObject<ITestCenterApi>();
        protected static readonly IAuthenticationContext authenticationContext = SpringContext.Current.GetObject<IAuthenticationContext>();

        #region Web Controls

        [Binding("TabContainer/TabPanelBody")]
        protected TextBox TextBoxTitle;

        [Binding("TabContainer/TabPanelBody")]
        protected TextBox TextBoxSummary;
              
        #endregion

        public override string Create()
        {
            TestProject testProject = new TestProject() {
                Name = TextBoxTitle.Text, Summary = TextBoxSummary.Text,
                CreatedBy = authenticationContext.User.UserId, 
                CreatedDate = DateTime.Now,IsParent = false };
            return testcenterApi.SaveTestProject(testProject, authenticationContext.DynamicParameter);
        }

        public override void LoadReadOnlyEntity(string entityId)
        {
            this.LoadWritableEntity(entityId);
            WebUtility.MakeBindingControlsReadOnly(this);
        }

        public override void LoadWritableEntity(string entityId)
        {
            using (TestCenterDataContext ctx = DataContextFactory.Create<TestCenterDataContext>())
            {
                var tp = ctx.TestProjects.FirstOrDefault(x => x.Id.ToString().Equals(entityId));
                if (tp != null)
                {
                    this.TextBoxTitle.Text = tp.Name;
                    this.TextBoxSummary.Text = tp.Summary;
                }
            }
        }

        public override void Update(string entityId)
        {
            using (TestCenterDataContext ctx = DataContextFactory.Create<TestCenterDataContext>())
            {
                var tp = ctx.TestProjects.FirstOrDefault(x => x.Id.ToString().Equals(entityId));
                if (tp != null)
                {
                    tp.Name = this.TextBoxTitle.Text ;
                    tp.Summary = this.TextBoxSummary.Text;
                }
                ctx.SubmitChanges();
            }
        }

       
    }
}
